<?php

// AJAX process START //
// init XAJAX
require_once App::getParam('path').'include/classes/xajax/xajax.inc.php';

function &loginBox($oRespX = null)
{
	if (!is_object($oRespX))
	{
		$oRespX = new xajaxResponse();	
	}
	
	$_SESSION['redirect_url'] = App::getPage();
	$oAccount = App::getModuleComponent('Account', 'Login', array('bDisplayCancel' => true));
	$sSrc = $oAccount->process();
	$oRespX->addAssign('popupLayer', 'innerHTML', $sSrc);
	$oRespX->addScript("sId('popupLayer').style.display='block';");
	return $oRespX;
}

function isUser()
{
	if ( App::getUser('id') != "" )
	{
		return;
	}

	exit('Invalid Post Data Being Sent!');
}

function _javascriptInfo($sInfo,$sTitle)
{
	$sBgColor = "green";
	$sInfos = "";
	if ( !empty($sInfo) )
	{
		$sBgColor = "red";
		$sInfos = " onmouseover=\"showInfo5('". $sInfo ."', '', '');\" onmouseout=\"return nd();\"";
	}
	return " <span style=\"color:#fff;padding-left:4px;padding-right:4px;background:". $sBgColor .";padding-bottom:2px;padding-top:2px;\"". $sInfos ."><b>". $sTitle ."</b></span> ";
}

function inviteUserToGroup($sMember, $iGroupId)
{
	isUser();

	$oRespX = new xajaxResponse();

	sleep(1);

    $oGroupsService = &App::getModuleService('Groups', 'Groups');
	$oMessengerService = &App::getModuleService('Messenger', 'Messenger');

	$aGroupData = $oGroupsService->getGroupData($iGroupId);

	if ( !isset($aGroupData['type']) )
	{
		return $oRespX;
	}

	//add member to group
	$oGroupsService->addInvite(App::getUser('user'), $sMember, $iGroupId, $aGroupData['type']);

	//send notification
	$sInviteText=App::format('Mod_Groups.mail_user_invited_to_group', array(App::makeUrl('public.groups.view', array('id' => $iGroupId)), $aGroupData['title']));
	$sInviteText = str_replace('<a href="' . App::makeUrl('public.groups.view', array('id' => $iGroupId)) . '">' . $aGroupData['title'] . '</a>', '[a="' . App::makeUrl('public.groups.view', array('id' => $iGroupId)) . '"]' . $aGroupData['title'] . '[/a]', $sInviteText);
	$oMessengerService->sendMessage(array('to'=>$sMember, 'title'=>App::format('Mod_Groups.title.invite'),'text'=>$sInviteText), App::getUser('user'), 'mail');

	$info = " [ ". App::format('Mod_Groups.user.invitied') ." ] ";
	$oRespX->addAssign("user_". $sMember ."","innerHTML",$info);

	return $oRespX;
}

function getFriendsList($sUser, $sFunction, $aParams, $sContent, $sValue)
{
	if ( !App::getUser('id') )
	{
		$oRespX = new xajaxResponse();
		$oRespX->addScript("document.getElementById('ajax_main_image').style.display='none';");
		$oRespX->addScript("alert('". App::format('Mod_Account.ajax.login') ."');");
		return $oRespX;
	}

	$oRespX = new xajaxResponse();

	if ( empty($sUser) )
	{
		$oRespX->addScript("document.getElementById('ajax_main_image').style.display='none';");
		$oRespX->addScript("alert('". App::format('Mod_Groups.empty.user') ."');");
		return $oRespX;
	}

	if ( !function_exists($sFunction) )
	{
		$oRespX->addScript("alert('Function ". $sFunction ." not found.');");
		return $oRespX;
	}

	sleep(1);

	$oDb = &Database::get();

	$aUsers = $oDb->getRows("SELECT id, user FROM ". App::getT('user') ."
		WHERE user LIKE '%". trim($oDb->escape($sUser)) ."%' LIMIT 20");

	$info = '<div style="padding:8px;">';
	if ( count($aUsers) >= 1 )
	{
		$info .= "". App::format($sContent) .": <ul>";
		foreach($aUsers as $aUser)
		{
			if ( empty($aUser['group_id']) )
			{
				$info .= '<li style="padding:4px;"><a href="javascript:void(0);" onclick="startRoutine(\'user_'. $aUser['user'] .'\'); xajax_'. $sFunction .'(\''. $aUser['user'] .'\', \''. $aParams .'\', \''. $sValue .'\');">'. $aUser['user'] .'</a><span id="user_'. $aUser['user'] .'"></span></li>';
			}
		}
		$info .= "</ul>";
	}
	else
	{
		$info .= App::format('Mod_Account.ajax.user.not');
	}
	$info .= "</div>";

	$oRespX->addScript("document.getElementById('ajax_main_image').style.display='none';");
	$oRespX->addAssign("update_check","innerHTML",$info);
	$oRespX->addScript("new Effect.Appear('update_check');");
	return $oRespX;

}

function getFriends($sUser, $iGroupId)
{
	isUser();

	$oRespX = new xajaxResponse();

	if ( empty($sUser) )
	{
		$oRespX->addScript("document.getElementById('ajax_main_image').style.display='none';");
		$oRespX->addScript("alert('". App::format('Mod_Groups.empty.user') ."');");
		return $oRespX;
	}

	sleep(1);

	$oDb = &Database::get();

	$oGroupsService = &App::getModuleService('Groups', 'Groups');

	$aUsers = $oDb->getRows("SELECT u.id, u.user, g.group_id FROM ". App::getT('user') ." AS u
		LEFT JOIN ". App::getT('group_invite') ." AS g ON (g.invite = u.user AND g.group_id = '". $iGroupId ."')
		WHERE u.user LIKE '%". trim($oDb->escape($sUser)) ."%' 
		GROUP BY u.user
		LIMIT 20");

	$i = 0;
	$info = '<div style="padding:8px;">';
	if ( count($aUsers) >= 1 )
	{
		$sub_info = "". App::format('Mod_Groups.click.users') .": <ul>";
		foreach($aUsers as $aUser)
		{
			$bIsMember = $oGroupsService->isMember($iGroupId, $aUser['user']);

			if ( !$bIsMember )
			{
				$i++;
				if (empty($aUser['group_id']))
				{
					$sub_info .= '<li style="padding:4px;"><a href="javascript:void(0);" onclick="startInvite(\'user_'. $aUser['user'] .'\'); xajax_inviteUserToGroup(\''. $aUser['user'] .'\', \''. $iGroupId .'\');">'. $aUser['user'] .'</a><span id="user_'. $aUser['user'] .'"></span></li>';
				}
				else 
				{
					$sub_info .= '<li style="padding:4px;"><a href="javascript:void(0);" onclick="if (confirm(\'' . App::format('Mod_Groups.group_invite_sent') . '\')) { startInvite(\'user_'. $aUser['user'] .'\'); xajax_inviteUserToGroup(\''. $aUser['user'] .'\', \''. $iGroupId .'\'); }">'. $aUser['user'] .'</a><span id="user_'. $aUser['user'] .'"> - ' . App::format('Mod_Groups.invite_pending') . '</span></li>';
				}
			}
		}
		$sub_info .= "</ul>";
	}
	$info .= ($i ? $sub_info : App::format('Mod_Groups.no.valid.users'));
	$info .= "</div>";

	$oRespX->addScript("document.getElementById('ajax_main_image').style.display='none';");
	$oRespX->addAssign("update_check","innerHTML",$info);
	$oRespX->addScript("new Effect.Appear('update_check');");
	return $oRespX;
}

function checkUsername($sUser)
{
	$oRespX = new xajaxResponse();
	$oDb = &Database::get();
	$oBanService = &App::getModuleService('Site', 'Ban');

	$checkIt = $oDb->getRow("SELECT `user` FROM `". App::getT('user') ."` WHERE `user` = '". $sUser ."'");

	if ( empty($sUser) )
	{
		$info = _javascriptInfo(App::format('Mod_Account.error.check_username'),App::format('Mod_Account.sign.fail'));
	}
    else if ( !eregi("[a-z]", substr($sUser, 0, 1)) )
	{
    	$info = _javascriptInfo(App::format('Mod_Account.first_must'), App::format('Mod_Account.sign.fail'));
    }	
	elseif ( !empty($checkIt['user']) )
	{
		$info = _javascriptInfo(App::format('Mod_Account.error.user_exists',$checkIt['user']),App::format('Mod_Account.sign.fail'));
	}
	else if (in_array(strtolower($sUser), $oBanService->getBlockedLogins()))
	{
	    $info = _javascriptInfo(App::format('Mod_Site.info.username_banned'), App::format('Mod_Account.sign.fail'));
	}
	else if( !$oBanService->checkDirs($sUser) )
	{
		$info = _javascriptInfo(App::format('Mod_Site.info.username_banned'), App::format('Mod_Account.sign.fail'));
	}
	else if (in_array($sUser, App::getParam('url.reserved_names')))
	{
	    $info = _javascriptInfo(App::format('Mod_Site.info.username_banned'), App::format('Mod_Account.sign.fail'));
	}	
	else
	{
		$info = _javascriptInfo("",App::format('Mod_Account.sign.ok'));
	}
	$oRespX->addScript("document.getElementById('ajax_main_image').style.display='none';");
	$oRespX->addAssign("update_check","innerHTML",$info);
	$oRespX->addScript("new Effect.Appear('update_check');");
	return $oRespX;
}

function newComment($aFormValue)
{
	isUser();

	$oRespX = new xajaxResponse();

	if ( empty($aFormValue['alert_id']) )
	{
		$oRespX->addScript("alert('". App::format('Mod_Comments.error.no_alert_id') ."')");
		$oRespX->addScript("sId('comment_submit_button').disabled=false;");
		return $oRespX;
	}

	App::loadClass('Text');
	$oTxt = &new Text();
	$oDb = &Database::get();
	$oCommentService = &App::getModuleService('Comments', 'Comment');

 	if (!$oCommentService->checkFlood())
    {
    	$oRespX->addScript("document.getElementById('ajax_main_image_cm').style.display='none';");
    	$oRespX->addScript("document.getElementById('ajax_main_form').style.display='';");
    	$oRespX->addScript("alert('". App::format('Mod_Comments.flooded', App::getSetting('flood_time')) ."');");
    	$oRespX->addScript("sId('comment_submit_button').disabled=false;");
    	return $oRespX;
	}

	$sStripped = strip_tags($aFormValue['val']['text'], '<img>');

	if (empty($sStripped))
    {
    	$oRespX->addScript("document.getElementById('ajax_main_image_cm').style.display='none';");
    	$oRespX->addScript("document.getElementById('ajax_main_form').style.display='';");
		$oRespX->addScript("alert('". App::format('Mod_Comments.error.no_text') ."');");
		$oRespX->addScript("sId('comment_submit_button').disabled=false;");
		return $oRespX;
	}

	if ( $aFormValue['ajax_type'] == 'account' )
	{
		$oFriendService = &App::getModuleService('Account', 'Friends');

		$aUser = $oDb->getRow("SELECT user, friends_comment FROM ". App::getT('user') ." WHERE id = '". $oDb->escape($aFormValue['ajax_id']) ."'");

		if ( $aUser['friends_comment'] && !$oFriendService->checkIsFriend(App::getUser('user'), $aUser['user']) && $aFormValue['ajax_id'] != App::getUser('id') )
		{
			$oRespX->addScript("document.getElementById('ajax_main_image_cm').style.display='none';");
    		$oRespX->addScript("document.getElementById('ajax_main_form').style.display='';");
			$oRespX->addScript("alert('". App::format('Mod_Comments.not_friend', $aUser['user']) ."');");
			$oRespX->addScript("sId('comment_submit_button').disabled=false;");
			return $oRespX;
		}

		if ( !App::getParam('profile_user_ocmnt') && $aFormValue['ajax_id'] == App::getUser('id'))
		{
			$oRespX->addScript("document.getElementById('ajax_main_image_cm').style.display='none';");
    		$oRespX->addScript("document.getElementById('ajax_main_form').style.display='';");
			$oRespX->addScript("alert('". App::format('Mod_Comments.no_can_do') ."');");
			$oRespX->addScript("sId('comment_submit_button').disabled=false;");
			return $oRespX;
		}
	}

	$sNewText = $oTxt->preParseText($aFormValue['val']['text']);
	$sNewText = $oTxt->utf8ToUnicode($sNewText);
	$iCid = $oCommentService->addComment(App::getParam('aCommentId',$aFormValue['ajax_type']), $aFormValue['ajax_id'], App::getUser('id'), $sNewText, $aFormValue['alert_id']);

	$aOwner = $oDb->getRow("SELECT `email`, `user`, `not_1` FROM `". App::getT('user') ."` WHERE `id` = '". $oDb->escape($aFormValue['alert_id']) ."'");

	switch($aFormValue['ajax_type'])
	{
		case 'gallery':
		$oCommentService->updateCounts('main', 'comment', "id = '". $aFormValue['ajax_id'] ."'", App::getParam('aCommentId',$aFormValue['ajax_type']), $aFormValue['ajax_id']);
		$sCommentUrl = App::makeUrl('public.gallery.view', array('id' => $aFormValue['ajax_id']));
		break;
		case 'account':
		$oCommentService->updateCounts('user', 'c_comments', "id = '". $aFormValue['ajax_id'] ."'", App::getParam('aCommentId', $aFormValue['ajax_type']), $aFormValue['ajax_id']);
		$sCommentUrl = App::makeUrl('public.user', array('name' => $aOwner['user']));
		break;
		case 'blog':
		$oCommentService->updateCounts('journal', 'comment', "id = '". $aFormValue['ajax_id'] ."'", App::getParam('aCommentId', $aFormValue['ajax_type']), $aFormValue['ajax_id']);
		$sCommentUrl = App::makeUrl('public.blog.view', array('id' => $aFormValue['ajax_id']));
		break;
		case 'music_album':
		$sCommentUrl = App::makeUrl('public.music.album', array('id' => $aFormValue['ajax_id']));
		break;
		case 'music_song':
		$sCommentUrl = App::makeUrl('public.music.song', array('id' => $aFormValue['ajax_id']));
		break;
		case 'video':
		$sCommentUrl = App::makeUrl('public.videos', array('id' => $aFormValue['ajax_id']));
		break;
	}

	$oSecurityService = &App::getModuleService('Account', 'Security');
	$oAccountService = &App::getModuleService('Account', 'Account');

	$oCurrentUser = $oSecurityService->getCurrentUser();

	$oAccountService->changeUserInfo($oCurrentUser, ($aFormValue['ajax_type'] == 'video' ? 'video_comment' : 'comment'));

	$aItem = array
	(
		'user' => App::getUser('user'),
		'text' => $sNewText,
		'time' => time(),
		'cid' => $iCid
	);

	$oTpl = &App::getTemplate();
	$oTpl->assignSrc(array
	(
		'aItem' => $aItem,
	));

	$sTemplate = $oTpl->fetch($oTpl->template_dir . '/_ajax/comments.html');
	$sTemplate = str_replace("'", "\'", $sTemplate);
	$sTemplate = str_replace("\r\n", "", $sTemplate);
	$sTemplate = str_replace(array("\n", "\t", "\r"), "", $sTemplate);
	$sTemplate = trim($sTemplate);	

	if ( isset($sCommentUrl) && $aOwner['not_1'] != 0 && App::getUser('id') != $aFormValue['alert_id'] )
	{
		$oMailer = &App::newObject('mail_Mailer');
    	$sSubject = App::format('core.comment');
    	$sTo = $aOwner['email'];
    	$aVars = array
		(
    	    'TO'           => $aOwner['user'],
    	    'FROM'         => App::getUser('user'),
			'SITENAME'     => App::getParam('url'),
			'HOME'         => App::getParam('url'),
			'COMMENT_LINK' => $sCommentUrl
    	);
		$oMailer->send('email_comment', $sTo, $sSubject, $aVars);
	}

	$oRespX->addAssign("ajax_main_image_cm","innerHTML", App::format('comment.added'));
	$oRespX->addScript("sId('new_comment_data').innerHTML = '". $sTemplate ."' + sId('new_comment_data').innerHTML;");
	$oRespX->addScript("setTimeout('sId(\'ajax_main_image_cm\').style.display=\'none\';', 4000)");
	$oRespX->addScript("new Effect.Appear('new_comment_data');");
	$oRespX->addScript("sId('total_count_comments').innerHTML=(parseInt(sId('total_count_comments').innerHTML) + 1);");
	$oRespX->addScript("sId('from_count_comments').innerHTML=(parseInt(sId('from_count_comments').innerHTML) + 1);");
	$oRespX->addScript("sId('comment_submit_button').disabled=false;");
	
	return $oRespX;
}

function listComments($iPage = 0, $sType = "", $iComments = 0)
{
	$oRespX = new xajaxResponse();

	$sParams = array
	(
		'type' => $sType,
		'page' => $iPage,
		'useajax' => true,
		'totalCount' => $iComments,
	);

	$oRespX->addScript("document.getElementById('comment_content').style.display='none';");

	$oSrvComments = &App::getModuleComponent('Comments', 'List', $sParams);
	$oRespX->addAssign("new_comment","innerHTML", $oSrvComments->process());

	$oRespX->addScript("document.getElementById('ajax_comment_loader').style.display='none';");

	return $oRespX;
}


// AJAX process END //

?>